#include <GLUT/glut.h>
#include <math.h>

const float PI = 3.141592;

GLfloat vFrame[8][3] = {
  {-.5,-0.5,-0.5},{-0.5,0.5,-0.5},{0.5,0.5,-0.5},{0.5,-0.5,-0.5},{0.5,-0.5,0.5},{0.5,0.5,0.5},{-0.5,0.5,0.5},{-0.5,-0.5,0.5} };

void draw() {
  glBegin(GL_LINE_LOOP);
  for ( int i = 0 ; i < 8 ; i++ ) {
    glVertex3fv(&vFrame[i][0]);
  }
  glEnd();
}

void drawBall(float swingAngle) {
  glPushMatrix();
  glTranslatef(0.8*sin(swingAngle*PI/180),0.8-0.8*cos(swingAngle*PI/180),0.0);
  glRotatef(swingAngle,0.0,0.0,1.0);
  glutWireSphere(0.1,10,10);
  glBegin(GL_LINES);
  glVertex3f(0.0,0.0,0.0);
  glVertex3f(0.0,0.8,0.5);
  glVertex3f(0.0,0.0,0.0);
  glVertex3f(0.0,0.8,-0.5);
  glEnd();
  glPopMatrix();
}

void drawBalls() {
  glTranslatef(0.3,-0.3,0.0);
  drawBall(0);
  glTranslatef(-0.2,0.0,0.0);
  drawBall(0);
  glTranslatef(-0.2,0.0,0.0);
  drawBall(0);
  glTranslatef(-0.2,0.0,0.0);
  drawBall(-45);
}

void display() {
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glColor3f(1.0, 1.0, 1.0);
  draw();
  drawBalls();
  glFlush();
}

void
init(void)
{
  glEnable( GL_DEPTH_TEST );
  glMatrixMode( GL_PROJECTION );
  glEnable(GL_LINE_SMOOTH);
  glLineWidth(1);
  glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

  glMatrixMode(GL_PROJECTION);
  gluPerspective( /* field of view in degree */ 40.0,
    /* aspect ratio */ 1.0,
    /* Z near */ 1.0, /* Z far */ 10.0);
  glMatrixMode(GL_MODELVIEW);

  gluLookAt(0.0, 0.0, 5.0,  /* eye is at (0,0,5) */
    0.0, 0.0, 0.0,      /* center is at (0,0,0) */
    0.0, 1.0, 0.);      /* up is in positive Y direction */

  glTranslatef(0.0, 0.0, 1.0);
  glRotatef(10.0, 1.0, 0.0, 0.0);
  glRotatef(20.0, 0.0, 1.0, 0.0);
}



int main( int argc, char **argv )
{
  glutInit(&argc,argv);
  glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);
  glutInitWindowSize(500,500);
  glutCreateWindow("Newton's Cradle");
  init();
  glutDisplayFunc(display);
  glutMainLoop();
  return 0;
}
